clear
discard
set more off

adopath ++ "./ado/"
adopath ++ "../tools/"
adopath ++ "../ssc/"

******************
*** Parameters ***
******************

local file_name "./input/consensus_dataset.csv"  // Data file
local output_folder "./output/aggregate_RR_shocks" // Output directory
local K = 4 // Number of lags to include when calculating local projections
local L = 20 // Number of IRF coefficients to estimate
local alpha = 0.05 // Significance level
local L_NW = 5 // Number of lags for calculating Newey-West standard errors

*************************************
*** Import data and set data type ***
*************************************

import delimited using `file_name', case(preserve)
rename DATE Date

gen qtr = quarterly(Date,"YQ")
format qtr %tq
tsset qtr // Set to time series

********************************
*** Generate forecast errors ***
********************************

gen Efor_Step2 = Realiz1 - SPFfor_Step2

***********************************
*** Calculate local projections ***
***********************************

estimate_IRF_external_IV Realiz1 FFR RR_shocks , k(`K') l(`L')
matrix IRF_actual_RR_shocks = e(s)

estimate_IRF_external_IV Efor_Step2 FFR RR_shocks , k(`K') l(`L')
matrix IRF_1Q_ahead_RR_shocks = e(s)

******************
*** Get graphs ***
******************

* Clean up
shell rm -r `output_folder'
shell mkdir -p ./output
shell mkdir `output_folder'

* Get plots
plot_IRF "IRF_actual_RR_shocks" `output_folder' "IRF_actual_RR_shocks"
plot_IRF "IRF_1Q_ahead_RR_shocks" `output_folder' "IRF_1Q_ahead_RR_shocks"

* Save estimated IRFs
mat2txt, matrix(IRF_actual_RR_shocks) saving(`output_folder'/IRF_actual_RR_shocks.txt)
mat2txt, matrix(IRF_1Q_ahead_RR_shocks) saving(`output_folder'/IRF_1Q_ahead_RR_shocks.txt)
